﻿#region License
// Copyright (c) 2012 Mund Consulting Ltd
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Collections;
using Microsoft.SharePoint.Utilities;
using System.Web;
namespace Mund.Sharepoint.Publishing
{
    public partial class NewPageLayout : LayoutsPageBase
    {
        const string constResource ="MundPublishingResource";
        const string constCoreResource = "wss";
        const string constMundPublishingContentTypeGroupName = "mundPublishingGroup";
        const string constPropertyHidden = "_Hidden";
        const string constCreateNewContentTypePagePath = "/_layouts/ctypenew.aspx";
        //const string constPageLayoutsLibraryTitle = "Page Layouts";
        const string constPageLayoutsLibraryTitle = "pageLayoutTitle";
        const string constPropertyTarget = "Target";
        const string constTargetValueBlank = "_blank";
        const string constPropertyTitle = "lstsetng_name_title";
        const string constPropertyComment = "versions_CommentsCol";
        const string constPrpertyContentType = "ContentType";
        const string constPropertyAssociatedContentType = "AssociatedContentType";
        const string constContenttypPageLayout = "pgeLayout";
        const string constAspxExtension = ".aspx";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SPWeb curWeb = SPContext.Current.Web;
                ArrayList contentTypeList = new ArrayList();
                ArrayList contentTypeGroupList = new ArrayList();
                foreach (SPContentType contentType in curWeb.AvailableContentTypes)
                {
                    contentTypeList.Add(contentType);
                }
                foreach (object lItem in contentTypeList)
                {
                    SPContentType currentCType = (SPContentType)lItem;
                    if (!contentTypeGroupList.Contains(currentCType.Group))
                    {
                        contentTypeGroupList.Add(currentCType.Group);
                        ddlContentGroup.Items.Add(currentCType.Group);
                    }

                }
                ddlContentGroup.Items.Remove(constPropertyHidden);
                ddlContentGroup.SelectedValue =Localization.GetValue(constResource,constMundPublishingContentTypeGroupName);

                SPContentTypeCollection ctypeCollection = curWeb.AvailableContentTypes;

                foreach (SPContentType cType in ctypeCollection)
                {
                    if (cType.Group == Localization.GetValue(constResource,constMundPublishingContentTypeGroupName))
                    {
                        ddlContentName.Items.Add(new ListItem(cType.Name, cType.Id.ToString()));
                    }
                }
                if (ddlContentName.Items.Count > 0)
                {
                    SPContentType ctype = ctypeCollection[new SPContentTypeId(ddlContentName.Items[0].Value)];
                    lblContentTypeDescription.Text = ctype.Description;
                }


                lnkNewContentType.HRef = curWeb.Url + constCreateNewContentTypePagePath;
                lnkNewContentType.Attributes[constPropertyTarget] = constTargetValueBlank;
            }
        }

        protected void ddlContentGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlContentName.Items.Clear();
            SPWeb curWeb = SPContext.Current.Web;
            SPContentTypeCollection ctypeCollection = curWeb.AvailableContentTypes;
            foreach (SPContentType cType in ctypeCollection)
            {
                if (cType.Group == ddlContentGroup.SelectedValue)
                {
                    ddlContentName.Items.Add(new ListItem(cType.Name, cType.Id.ToString()));
                }
            }

            if (ddlContentName.Items.Count > 0)
            {
                SPContentType ctype = ctypeCollection[new SPContentTypeId(ddlContentName.Items[0].Value)];
                lblContentTypeDescription.Text = ctype.Description;
            }

        }
        protected void ddlContentName_SelectedIndexChanged(object sender, EventArgs e)
        {
            SPContentTypeId contentTypeId = new SPContentTypeId(ddlContentName.SelectedValue);
            SPWeb curWeb = SPContext.Current.Web;
            SPContentType cType = curWeb.AvailableContentTypes[contentTypeId];
            lblContentTypeDescription.Text = cType.Description;

        }

        protected void CreatePageLayout(object sender, EventArgs e)
        {
            SPWeb curWeb = SPContext.Current.Web;
            SPList libPageLayout = curWeb.Lists.TryGetList(Localization.GetValue(constResource,constPageLayoutsLibraryTitle));
            if (libPageLayout == null)
            {
                return;
            }
            SPFolder pageLayoutFolder = libPageLayout.RootFolder;
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            string strTemplate = GetTemplate();
            writer.Write(strTemplate);
            writer.Flush();
            pageLayoutFolder.Files.Add(tbxUrlName.Text + constAspxExtension, stream, true);
            SPFile file = pageLayoutFolder.Files[tbxUrlName.Text + constAspxExtension];
            SPListItem item = file.Item;
            item[Localization.GetValue(constCoreResource, constPropertyTitle)] = tbxTitle.Text;
            item[Localization.GetValue(constCoreResource, constPropertyComment)] = tbxDesc.Text;
            //item["ContentTypeId"] = ddlContentName.SelectedValue;
            item[constPrpertyContentType] = Localization.GetValue(constResource, constContenttypPageLayout);
            //item["ContentType"] = "Page Layout";
            SPFieldMultiColumnValue val = new SPFieldMultiColumnValue(3);
            val[0] = ddlContentGroup.SelectedValue;
            val[1] = ddlContentName.SelectedItem.Text;
            val[2] = ddlContentName.SelectedValue;
            item[constPropertyAssociatedContentType] = val;
            item.Update();
            SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, Context);
        }
        protected void DoCancel(object sender, EventArgs e)
        {
            SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, Context);
        }

        private String GetTemplate()
        {
            StringBuilder strContents = new StringBuilder();
            strContents.AppendLine(@"<%@ Page language=""C#"" MasterPageFile=""~masterurl/custom.master""   Inherits=""Mund.Sharepoint.Publishing.MundPublishingPage,Mund.Sharepoint.Publishing,Version=1.0.0.0,Culture=neutral,PublicKeyToken=76ac3abf0faf5e48"" meta:progid=""SharePoint.WebPartPage.Document"" meta:webpartpageexpansion=""full""  %>");
            strContents.AppendLine(@"<%@ Register Tagprefix=""SharePoint"" Namespace=""Microsoft.SharePoint.WebControls"" Assembly=""Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %> <%@ Register Tagprefix=""Utilities"" Namespace=""Microsoft.SharePoint.Utilities"" Assembly=""Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %> <%@ Import Namespace=""Microsoft.SharePoint"" %> <%@ Assembly Name=""Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %> <%@ Register Tagprefix=""WebPartPages"" Namespace=""Microsoft.SharePoint.WebPartPages"" Assembly=""Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %>");
            strContents.AppendLine(@"<%@ Register TagPrefix=""MundPublishing"" TagName=""PageEdit"" src=""~/_CONTROLTEMPLATES/Mund.Sharepoint.Publishing/EditFieldControl.ascx"" %>");
            strContents.AppendLine(@"<asp:Content ContentPlaceholderID=""PlaceHolderPageTitle"" runat=""server""><SharePoint:FieldValue id=""PageTitle"" FieldName=""Title"" runat=""server""/></asp:Content>");
            strContents.AppendLine(@"<asp:Content ContentPlaceholderID=""PlaceHolderMain"" runat=""server"">");
            strContents.AppendLine(@"<div><h1 class=""ms-rteElement-H1B"" style=""margin-bottom:0px""><span><span>");
            strContents.AppendLine(@"<MundPublishing:PageEdit id=""PageEditTitle_Default""  runat=""server""");
            strContents.AppendLine(@"FieldName=""" + Localization.GetValue(constCoreResource, constPropertyTitle) + "\"/>");
            strContents.AppendLine(@"</span></span></h1><div></div></div></asp:Content>");
            return strContents.ToString();
        }

    

    }
}
